<template>
  <view class="container">
    <view class="background-container">
      <image class="header-bg" src="@/static/headerBgi2.png" mode="widthFix">
      </image>
    </view>
    <view class="status-bar" v-if="!isApp"></view>
    <view class="navbar">
      <image class="navbarImg" @click="goBack" src="@/static/back.png" mode="aspectFill"></image>
      报名登记
    </view>
    <view class="content">
      <view class="userInfo">
        <view class="tetx">
          <view class="label">姓名<text class="required">*</text></view>
          <input v-model="name" placeholder="请输入您的姓名" class="filed" maxlength="20" @input="onNameInput" />
        </view>
        <view class="tetx">
          <view class="label">性别<text class="required">*</text></view>
          <picker v-model="genderIndex" class="filed" mode="selector" :range="genderOptions" range-key="text"
            @change="onGenderChange">
            <view :style="{color:'#7f8387',fontSize:'30rpx',display:'inline-block'}">{{genderOptions[genderIndex].text}}
            </view>
            <image src="@/static/chooseGender.png"></image>
          </picker>
          <!-- 性别 picker 
          <picker  mode="selector" :range="genderOptions" range-key="text" @change="onGenderChange">
            <view :style="{color:'#7f8387',fontSize:'30rpx',display:'inline-block'}">
              {{ genderOptions[genderIndex]?.text || '请选择性别' }}
            </view>
            <image src="../../static/选择性别ico.png"></image>
          </picker> -->
        </view>
        <view class="tetx">
          <view class="label">出生日期<text class="required">*</text></view>
          <picker class="filed" mode="date" fields="year-month" @change="onBirthdayChange" :end="endDate">
            <view :style="{color:'#7f8387',fontSize:'30rpx',display:'inline-block'}">
              {{birthday || '请选择出生日期'}}
            </view>
            <image src="@/static/chooseGender.png"></image>
          </picker>
        </view>
      </view>
      <view class="diviler"></view>
      <view class="collegeInfo">
        <view class="tetx">
          <view class="label">在读院校学院<text class="required">*</text></view>
          <!-- 学校 -->
          <input v-model="college" placeholder="请输入学校名称" class="filed" maxlength="50" @input="onCollegeInput" />
        </view>
        <view class="tetx">
          <view class="label">专业<text class="required">*</text></view>
          <!-- 专业 -->
          <input v-model="major" placeholder="请输入专业名称" class="filed" maxlength="50" @input="onMajorInput" />
        </view>
        <view class="tetx">
          <view class="label">年级<text class="required">*</text></view>
          <input class="filed" type="text" v-model="gradeValue" placeholder="请输入年级"
            :style="{color:'#7f8387',fontSize:'30rpx',display:'inline-block'}" maxlength="10" @input="onGradeInput" />
        </view>
      </view>
    </view>
    <view class="diviler"></view>
    <view class="pdfInfo">
      <view class="pdf">
        <view class="label">报名表附件<text class="required">*</text></view>
        <view class="downLoand" @click="downloadFile">
          <view :style="{display:'inline-block',color:'#3b7de8',fontSize:'30rpx'}">下载模板</view>
          <image src="@/static/downLoad.png"></image>
        </view>
      </view>
      <view v-if="!isUploaded">
        <view class="document">
          <view class="pdfBackground">
            <image src="@/static/uploadFileBgi.png" class="bacImage"></image>
          </view>
          <view class="uploadContainer" @click="handleUpload">
            <image src="@/static/uploadFileBtn.png" class="push"></image>
            <view class="tip">上传附件</view>
          </view>
        </view>
        <view class="remaind" :style="{marginTop:'24rpx'}">
          <view :style="{color:'#3b7de8',fontSize:'26rpx',display:'initial'}"> 温馨提示：</view>
          <view :style="{color: '#7f8387',fontSize:'26rpx',display:'initial'}">
            请上传pdf格式附件
          </view>
        </view>
      </view>

      <view v-else>
        <view class="pushOk">
          <image src="@/static/pdf.png" :style="{height:'70rpx',width:'56rpx'}"></image>
          <text class="fileName">{{shortFileName}}</text>
          <image src="@/static/clearFileBtn.png" :style="{width:'30rpx',height:'30rpx',marginRight:'12rpx'}"
            @click="clean"></image>
        </view>
      </view>
    </view>
  </view>
  <view class="bottom">
    <button @click="goBack"
      :style="{color:'#b7bbbe',border:'2rpx #b7bbbe',borderRadius:'10rpx',display:'inline-block',marginRight:'16rpx'}">返回</button>
    <button @click="handleSignUp"
      :style="{color:'#ffffff',backgroundColor:'#3b7de8',borderRadius:'10rpx',display:'inline-block'}">确认提交</button>
  </view>
</template>

<script setup>
  import {
    onLoad
  } from '@dcloudio/uni-app'
  import {
    signupApi
  } from '@/api/signup/signup.js';
  import {
    ref,
    computed
  } from 'vue';
  import {
    http
  } from '@/utils/http.js';
  import {
    baseURL
  } from '@/utils/http.js';
  import {
    getQuestByid,
    downloadRequirementDoc
  } from '@/api/detail/position.js';
  const genderOptions = ref([{
      text: '男',
      value: 1
    },
    {
      text: '女',
      value: 2
    }
  ])
  // const gradeOption = ref([
  //   "大一",
  //   "大二",
  //   "大三",
  //   "大四",
  //   "研究生"
  // ])
  const name = ref(''); // 姓名
  const genderIndex = ref(0); // 性别索引
  const genderValue = ref(genderOptions.value[genderIndex.value].value); // 性别值
  const birthday = ref('2000-01-01'); // 出生年月，默认值为2000-01-01
  const college = ref(''); // 学校
  const major = ref(''); // 专业
  const gradeValue = ref(''); // 年级
  const isUploaded = ref(false); // 是否已上传附件
  const fileName = ref('')
  const requireId = ref('')
  const now = new Date();
  const endDate = ref(
    `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`
  );
  const startDate = ref('2000-01-01');
  const onGenderChange = (e) => {
    genderIndex.value = e.detail.value
    genderValue.value = genderOptions.value[e.detail.value].value
  }

  const onBirthdayChange = (e) => {
    birthday.value = e.detail.value
  }

  const onGradeChange = (e) => {
    gradeValue.value = gradeOption.value[e.detail.value]
  }
  const goBack = () => {
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];

    console.log('当前页面:', currentPage);
    console.log('页面参数:', currentPage.options);
    console.log(currentPage.options.requireId)



    var num = pages.length
    var backNum
    for (var i = 0; i < num; i++) {
      console.log(pages[i].route)
      if (pages[i].route == '/pages/signup/signup') {
        backNum = num - i - 1
      }
    }
    if (currentPage.options.requireId) {
      uni.navigateBack({
        delta: backNum
      })
    } else {
      uni.showToast({
        title: '参数错误',
        icon: 'none'
      });
    }
  };

  const token = uni.getStorageSync('token');

  const handleUpload = async () => {
    try {
      const res = await signupApi.uploadFile({
        count: 1,
        extensions: ['.pdf'],
        url: `${baseURL}/upload`,
        header: {
          'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
        },
        formData: []
      });

      console.log('上传成功:', res);
      isUploaded.value = true
      const FileName = res.filename;
      const fullPath = res.url;

      // 以 "/profile/upload/" 为分隔符拆分
      const result = fullPath.split("/profile/upload/")[1];
      // 输出: 2025/07/19/查看成绩_001 (6)1752910161881.pdf
      fileName.value = result;
      const filePath = {
        value: result
      };
      console.log(filePath);
      uni.setStorageSync('filePath', filePath);

      const uploadFileName = {
        value: FileName
      };
      console.log(uploadFileName);
      uni.setStorageSync('fileName', uploadFileName)

      uni.showToast({
        title: '上传成功'
      });
    } catch (error) {
      console.error('上传失败:', error);
      uni.showToast({
        title: '上传失败',
        icon: 'none'
      });
    }
  };
  // const admit = () => {
  //   isUploaded.value = true
  //   fileName.value = '报名表.pdf'
  //   uni.navigateTo({
  //     url: "/pages/registered/registered"
  //   })
  // }
  const clean = () => {
    isUploaded.value = false
    fileName.value = ''
  }
  onLoad((options) => {
    console.log(options)
    // 1. 获取参数
    if (options.requireId) {
      console.log(options.requireId)
      requireId.value = options.requireId;
      // 2. 调用接口
      signupApi.linkSignUp(options.requireId).then(res => {
        // TODO 缺少已经报名逻辑
        if (res.code === 200 && res.data) {
          name.value = res.data.name;
          genderIndex.value = res.data.genderIndex;
          genderValue.value = res.data.gender;
          genderIndex.value = genderOptions.value.findIndex(item => item.value === res.data.gender);
          birthday.value = res.data.birthday;
          college.value = res.data.college;
          major.value = res.data.major;
          gradeValue.value = res.data.grade;
          // uni.showToast({
          //   title: '数据加载成功'
          // });
        }
        // else {
        //   uni.showToast({
        //     // title: '加载失败',
        //     icon: 'none'
        //   });
        // }
      })
    } else {
      uni.showToast({
        title: '缺少必要参数',
        icon: 'none'
      });
      console.warn('参数缺失:', options);
    }
  })

  // 提交表单
  const handleSignUp = () => {


    if (
      !name.value.trim() ||
      !genderValue.value ||
      !birthday.value.trim() ||
      !college.value.trim() ||
      !major.value.trim() ||
      !gradeValue.value.trim() ||
      !fileName.value.trim()
    ) {
      uni.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    const busSignup = {
      name: name.value,
      gender: genderValue.value,
      birthday: birthday.value,
      college: college.value,
      major: major.value,
      grade: gradeValue.value,
      fileUrl: fileName.value,
      requireId: requireId.value,
    };

    uni.showModal({
      title: '提示',
      content: '只能同时报名一个岗位，确定要提交吗？',
      confirmText: '确定',
      cancelText: '取消',
      success: function(res) {
        if (res.confirm) {
          doSignUp();
        }
      }
    });
  };

  const doSignUp = () => {
    const busSignup = {
      name: name.value,
      gender: genderValue.value,
      birthday: birthday.value,
      college: college.value,
      major: major.value,
      grade: gradeValue.value,
      fileUrl: fileName.value,
      requireId: requireId.value,
    };

    console.log(busSignup);

    if (
      !busSignup.name?.trim() ||
      !busSignup.gender ||
      !busSignup.birthday?.trim() ||
      !busSignup.college?.trim() ||
      !busSignup.major?.trim() ||
      !busSignup.grade?.trim() ||
      !busSignup.fileUrl?.trim()
    ) {
      uni.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    signupApi.signUp(busSignup).then(res => {
      console.log('提交报名接口响应:', res);
      if (res.code == 200) {
        console.log(111)
        uni.showToast({
          title: '报名成功',
          icon: 'success'
        });
        uni.redirectTo({
          url: '/pages/registered/registered'
        });
      }
    }).catch(res => {
      uni.showToast({
        title: res.msg || '报名失败',
        icon: 'none'
      });
    })
  };

  const downloadFile = async () => {
    try {
      uni.showLoading({
        title: '准备下载...'
      });

      await downloadRequirementDoc();

      uni.hideLoading();
      uni.showToast({
        title: '下载已开始',
        icon: 'success',
        duration: 2000
      });
    } catch (error) {
      console.error('下载失败:', error);
      uni.hideLoading();
      uni.showToast({
        title: error.message || '下载失败',
        icon: 'none',
        duration: 2000
      });
    }
  };

  const onNameInput = (e) => {
    if (e.detail.value.length >= 20) {
      uni.showToast({
        title: '已到最大输入长度',
        icon: 'none'
      });
    }
    name.value = e.detail.value.slice(0, 20);
  };
  const onCollegeInput = (e) => {
    if (e.detail.value.length >= 50) {
      uni.showToast({
        title: '已到最大输入长度',
        icon: 'none'
      });
    }
    college.value = e.detail.value.slice(0, 50);
  };
  const onMajorInput = (e) => {
    if (e.detail.value.length >= 50) {
      uni.showToast({
        title: '已到最大输入长度',
        icon: 'none'
      });
    }
    major.value = e.detail.value.slice(0, 50);
  };
  const onGradeInput = (e) => {
    if (e.detail.value.length >= 10) {
      uni.showToast({
        title: '已到最大输入长度',
        icon: 'none'
      });
    }
    gradeValue.value = e.detail.value.slice(0, 10);
  };

  const shortFileName = computed(() => {
    if (!fileName.value) return '';
    const parts = fileName.value.split('/');
    return parts[parts.length - 1];
  });
</script>

<style>
  .container {
    position: relative;
    width: 100%;
    padding-bottom: 100rpx;
  }

  .background-container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 128rpx;
    overflow: hidden;
    z-index: -1;
  }

  .header-bg {
    width: 100%;
    height: 100%;
  }

  .status-bar {
    height: var(--status-bar-height);
  }

  .navbar {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 36rpx;
    text-align: center;
    height: calc(128rpx - var(--status-bar-height));
    position: relative;
  }

  .navbarImg {
    position: absolute;
    left: 21rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 19rpx;
    height: 33rpx;
  }

  .userInfo {
    margin: 0 30rpx;
  }

  .collegeInfo {
    margin: 0 30rpx;
  }

  .diviler {
    background-color: #f8f8f8;
    height: 12rpx;
    width: 100%;
  }

  .tetx {
    padding: 34rpx 0;
    display: flex;
    align-items: center;
    border-bottom: 1rpx solid #f4f4f4;
    width: 690rpx;
    justify-content: space-between;
  }

  .label {
    color: #474b53;
    font-size: 30rpx;
  }

  .required {
    color: #FF0000;
    margin-left: 4rpx;
    font-size: 30rpx;
  }

  .filed {
    color: #474b53;
    flex: 1;
    font-size: 30rpx;
    text-align: right;
    align-items: center;
    justify-content: center;
  }

  .filed image {
    width: 8rpx;
    height: 16rpx;
    display: inline-block;
    margin-left: 14rpx;
  }

  .pdfInfo {
    margin: 0 30rpx;
  }

  .pdf {
    display: flex;
    padding: 34rpx 0;
    align-items: center;
    justify-content: center;
  }

  .downLoand {
    flex: 1;
    text-align: right;
  }

  .downLoand image {
    width: 23rpx;
    height: 25rpx;
    margin-left: 11rpx;
  }

  .document {
    position: relative;
    height: 118rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .pdfBackground {
    position: absolute;
    height: 118rpx;
    width: 690rpx;
    z-index: -1;
  }

  .bacImage {
    height: 100%;
    width: 100%;
  }

  .push {
    width: 35rpx;
    height: 38rpx;
  }

  .tip {
    color: #3b7de8;
    font-size: 20rpx;
  }

  .uploadContainer {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    height: 100%;
  }

  .fileName {
    flex: 1;
    margin-left: 20rpx;
    display: flex;
  }

  .pushOk {
    background-color: #f8f9fd;
    border-radius: 10rpxs;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 24rpx;
  }

  .bottom {
    bottom: 0;
    left: 0;
    right: 0;
    box-shadow: 0 -1rpx 8rpx rgba(0, 0, 0, 0.05);
    padding: 17rpx 30rpx;
    position: fixed;
  }

  .bottom button {
    width: 337rpx;
    height: 64rpx;
    line-height: 64rpx;
    text-align: center;
    border-radius: 10rpx;
    /* 不要加display: flex; */
  }
</style>